package com.kyrie.security.jwt;

import com.kyrie.utils.GlobalConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/***
 * 描述: 自定义JWTFilter过滤器，对token进行认证处理
 * 所有需要认证的请求都会到当前过滤器中，配置为anon无认证的请求不会到该过滤器
 *
 * @author wuxiang
 * @date 2020-04-07 10:51
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /***
     * 持有token进行认证
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // 始终返回false来执行onAccessDenied方法
        return false;
    }


    /**
     * 当isAccessAllowed返回false时会执行该方法
     * 重定向到/500进行controller处理返回响应结果信息
     * @param request ServletRequest
     * @param response ServletResponse
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 获取请求头上的token信息
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader(GlobalConstants.SECURITY_TOKEN);

        if (StringUtils.isEmpty(token)) {
            // 针对error的中文错误信息重定向后会乱码的解决方案，对errorMsg进行编码即可
            httpResponse.sendRedirect("/500?errorMsg=" + URLEncoder.encode(GlobalConstants.TOKEN_LOSS_MSG,"UTF-8"));
            return false;
        }

        // 执行token认证
        try {
            // 委托 realm 进行登录认证
            JWTToken jwtToken = new JWTToken(token);
            getSubject(request,response).login(jwtToken);
            return true;
        } catch (Exception e) {
            responseError(response, e.getMessage());
            return false;
        }
    }

    /***
     * 添加跨域支持
     * @param request ServletRequest
     * @param response ServletResponse
     * @return boolean
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setHeader("Access-control-Allow-Origin", httpRequest.getHeader("Origin"));
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 将非法请求跳转到 /500?errorMsg=xxx
     */
    private void responseError(ServletResponse response, String message) {
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //设置编码，否则中文字符在重定向时会变为空字符串
            httpServletResponse.sendRedirect("/500?errorMsg=" + URLEncoder.encode(message, "UTF-8"));

        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
}
